<template>
  <div class="admin-posts-view">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <div class="header-title">
            <h1>📝 帖子管理</h1>
            <p>管理系统中的所有帖子，维护内容质量</p>
          </div>
        </div>
        <div class="header-stats">
          <div class="stat-item">
            <div class="stat-number">{{ total }}</div>
            <div class="stat-label">总帖子数</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选器 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filters" inline class="filter-form">
        <el-form-item label="关键词">
          <el-input
            v-model="filters.keyword"
            placeholder="搜索标题或内容"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="分类">
          <el-select
            v-model="filters.categoryId"
            placeholder="选择分类"
            clearable
            style="width: 150px"
          >
            <el-option label="全部分类" value="" />
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filters.status" placeholder="选择状态" clearable style="width: 120px">
            <el-option label="全部" value="" />
            <el-option label="正常" :value="1" />
            <el-option label="已删除" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetFilters">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 当前筛选条件 -->
    <div v-if="hasActiveFilters" class="filter-status">
      <div class="filter-status-header">
        <span class="filter-status-title">当前筛选条件</span>
        <el-button type="danger" plain size="small" @click="resetFilters">
          <el-icon><Close /></el-icon>
          清除所有筛选
        </el-button>
      </div>
      <div class="filter-tags">
        <el-tag
          v-if="filters.keyword"
          type="primary"
          closable
          @close="
            filters.keyword = '';
            handleSearch();
          "
        >
          关键词: {{ filters.keyword }}
        </el-tag>
        <el-tag
          v-if="filters.categoryId"
          type="success"
          closable
          @close="
            filters.categoryId = '';
            handleSearch();
          "
        >
          分类: {{ getCategoryName(filters.categoryId) }}
        </el-tag>
        <el-tag
          v-if="filters.status !== ''"
          type="warning"
          closable
          @close="
            filters.status = '';
            handleSearch();
          "
        >
          状态: {{ getStatusName(filters.status) }}
        </el-tag>
      </div>
    </div>

    <!-- 帖子列表 -->
    <el-card class="posts-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>帖子列表 (共 {{ total }} 条)</span>
          <div class="header-actions">
            <el-button type="primary" @click="loadPosts" :loading="loading" size="small">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="posts"
        v-loading="loading"
        style="width: 100%"
        :empty-text="loading ? '加载中...' : '暂无数据'"
        stripe
        @sort-change="handleSortChange"
      >
        <el-table-column prop="id" label="ID" width="80" sortable />
        <el-table-column label="标题" min-width="200">
          <template #default="{ row }">
            <div class="post-title">
              <el-tag v-if="row.isTop" type="danger" size="small" effect="dark">置顶</el-tag>
              <span class="title-text" :title="row.title">{{ row.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="作者" width="140">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :src="row.author?.avatar" :size="32">
                {{ row.author?.username?.charAt(0) }}
              </el-avatar>
              <span class="username">{{ row.author?.username }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="分类" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.category" type="primary" size="small">{{ row.category.name }}</el-tag>
            <span v-else class="text-muted">无分类</span>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180" sortable prop="createTime">
          <template #default="{ row }">
            <div class="time-info">
              <div>{{ formatTime(row.createTime) }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button size="small" type="info" plain @click="viewPost(row)">
                <el-icon><View /></el-icon>
                查看
              </el-button>
              <el-button
                v-if="row.status === 'published'"
                type="warning"
                size="small"
                @click="toggleTop(row)"
                plain
              >
                <el-icon><Top /></el-icon>
                {{ row.isTop ? "取消置顶" : "置顶" }}
              </el-button>
              <el-button
                :type="row.status === 'published' ? 'danger' : 'success'"
                size="small"
                @click="toggleStatus(row)"
                plain
              >
                <el-icon>
                  <Delete v-if="row.status === 'published'" />
                  <RefreshRight v-else />
                </el-icon>
                {{ row.status === "published" ? "删除" : "恢复" }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Refresh, Close, View, Top, Delete, RefreshRight } from "@element-plus/icons-vue";
import { getAdminPosts, deleteAdminPost, restoreAdminPost, togglePostTop } from "@/api/admin";
import { getCategories } from "@/api/categories";
import type { Post, Category } from "@/types";

const router = useRouter();

// 响应式数据
const loading = ref(false);
const posts = ref<Post[]>([]);
const categories = ref<Category[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(20);

// 筛选条件
const filters = reactive({
  keyword: "",
  categoryId: "" as string | number,
  status: "" as string | number,
});

// 加载帖子列表
const loadPosts = async () => {
  loading.value = true;
  try {
    const params: {
      page: number;
      size: number;
      keyword?: string;
      categoryId?: string | number;
      status?: string | number;
    } = {
      page: currentPage.value,
      size: pageSize.value,
    };

    // 添加筛选条件
    if (filters.keyword) {
      params.keyword = filters.keyword;
    }
    if (filters.categoryId) {
      params.categoryId = filters.categoryId;
    }
    if (filters.status !== "") {
      params.status = filters.status;
    }

    const response = await getAdminPosts(params);

    const responseData = response as { items?: any[]; total?: number };
    posts.value = (responseData?.items?.map(
      (post: {
        id: number;
        author?: { id?: number; username?: string; avatar?: string };
        category?: { id?: number; name?: string };
        title: string;
        content: string;
        summary?: string;
        viewCount: number;
        likeCount: number;
        commentCount: number;
        isTop: boolean;
        status: number;
        createdAt: string;
        updatedAt: string;
      }) => ({
        id: post.id,
        userId: post.author?.id || 0,
        categoryId: post.category?.id || 0,
        title: post.title,
        content: post.content,
        excerpt: post.summary,
        viewCount: post.viewCount,
        likeCount: post.likeCount,
        commentCount: post.commentCount,
        isTop: post.isTop,
        status: getStatusFromCode(post.status),
        createTime: post.createdAt,
        updateTime: post.updatedAt,
        author: post.author,
        category: post.category,
      })
    ) || []) as Post[];

    total.value = responseData?.total || 0;
  } catch (error: unknown) {
    console.error("Failed to load posts:", error);

    const err = error as { response?: { status?: number }; code?: string };
    if (err?.response?.status === 403) {
      ElMessage.error("权限不足，无法访问帖子管理");
    } else if (err?.response?.status === 401) {
      ElMessage.error("登录已过期，请重新登录");
    } else if (err?.code === "NETWORK_ERROR") {
      ElMessage.error("网络连接失败，请检查网络");
    } else {
      ElMessage.error("加载帖子列表失败，请稍后重试");
    }

    posts.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 加载分类列表
const loadCategories = async () => {
  try {
    const response = await getCategories();
    categories.value = response;
  } catch (error: unknown) {
    console.error("Failed to load categories:", error);
    ElMessage.warning("加载分类列表失败，筛选功能可能受影响");
    categories.value = [];
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  loadPosts();
};

// 重置筛选
const resetFilters = () => {
  filters.keyword = "";
  filters.categoryId = "";
  filters.status = "";
  handleSearch();
};

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  loadPosts();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadPosts();
};

// 排序处理
const handleSortChange = (sortData: { prop: string; order: string | null }) => {
  console.log("排序变化:", sortData);
  // 这里可以根据需要实现排序逻辑
  // 暂时不实现后端排序，前端表格会自动处理
};

// 查看帖子
const viewPost = (post: Post) => {
  const routeData = router.resolve(`/posts/${post.id}`);
  window.open(routeData.href, "_blank");
};

// 切换置顶状态
const toggleTop = async (post: Post) => {
  try {
    await ElMessageBox.confirm(
      `确定要${post.isTop ? "取消置顶" : "置顶"}这篇帖子吗？`,
      "确认操作",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    await togglePostTop(post.id, !post.isTop);
    ElMessage.success(`${post.isTop ? "取消置顶" : "置顶"}成功`);
    loadPosts();
  } catch (error) {
    if (error !== "cancel") {
      console.error("Toggle top failed:", error);
      ElMessage.error("操作失败");
    }
  }
};

// 切换状态
const toggleStatus = async (post: Post) => {
  try {
    await ElMessageBox.confirm(
      `确定要${post.status === "published" ? "删除" : "恢复"}这篇帖子吗？`,
      "确认操作",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    if (post.status === "published") {
      // 删除帖子
      await deleteAdminPost(post.id);
      ElMessage.success("删除成功");
    } else {
      // 恢复帖子
      await restoreAdminPost(post.id);
      ElMessage.success("恢复成功");
    }

    loadPosts();
  } catch (error) {
    if (error !== "cancel") {
      console.error("Toggle status failed:", error);
      ElMessage.error("操作失败");
    }
  }
};

// 格式化时间
const formatTime = (time: string) => {
  return new Date(time).toLocaleString();
};

// 获取状态文本
const getStatusText = (status: string) => {
  if (status === "published") {
    return "正常";
  } else if (status === "draft") {
    return "草稿";
  } else if (status === "deleted") {
    return "已删除";
  }
  return "未知";
};

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  if (status === "published") {
    return "success";
  } else if (status === "draft") {
    return "info";
  } else if (status === "deleted") {
    return "danger";
  }
  return "info";
};

// 从状态码获取状态
const getStatusFromCode = (code: number) => {
  if (code === 1) {
    return "published";
  } else if (code === 0) {
    return "deleted";
  }
  return "draft";
};

// 检查是否有活动筛选
const hasActiveFilters = computed(() => {
  return !!(filters.keyword || filters.categoryId || filters.status !== "");
});

// 根据ID获取分类名称
const getCategoryName = (categoryId: string | number) => {
  const category = categories.value.find(c => c.id === categoryId);
  return category ? category.name : "未知分类";
};

// 根据状态值获取状态名称
const getStatusName = (status: string | number) => {
  if (status === 1) {
    return "正常";
  } else if (status === 0) {
    return "已删除";
  }
  return "未知状态";
};

// 组件挂载
onMounted(() => {
  loadPosts();
  loadCategories();
});
</script>

<style scoped lang="scss">
.admin-posts-view {
  .page-header {
    margin-bottom: 24px;
    background-color: #f5f7fa;
    padding: 20px 24px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .header-left {
      .header-title {
        h1 {
          margin: 0 0 8px 0;
          font-size: 24px;
          color: #2c3e50;
        }

        p {
          margin: 0;
          color: #666;
        }
      }
    }

    .header-stats {
      display: flex;
      align-items: center;
      gap: 24px;

      .stat-item {
        text-align: center;

        .stat-number {
          font-size: 24px;
          font-weight: 700;
          color: #409eff;
          margin-bottom: 4px;
        }

        .stat-label {
          font-size: 12px;
          color: #666;
        }
      }
    }
  }

  .filter-status {
    margin-bottom: 24px;
    padding: 16px;
    background-color: #fafbfc;
    border: 1px solid #e5e7eb;
    border-radius: 8px;

    .filter-status-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;

      .filter-status-title {
        font-weight: 600;
        color: #374151;
        font-size: 14px;
      }
    }

    .filter-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      .el-tag {
        border-radius: 4px;
        font-size: 12px;
      }
    }
  }

  .filter-card {
    margin-bottom: 24px;

    .filter-form {
      margin-bottom: 0;
    }
  }

  .posts-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 600;
      color: #2c3e50;
    }

    .post-title {
      display: flex;
      align-items: center;
      .el-tag {
        margin-right: 8px;
      }
      .title-text {
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

    .user-info {
      display: flex;
      align-items: center;
      gap: 8px;

      .username {
        font-size: 14px;
      }
    }

    .action-buttons {
      display: flex;
      flex-wrap: wrap;
      gap: 6px;
      align-items: center;

      .el-button {
        margin: 0;
        font-size: 12px;
        padding: 5px 8px;
        border-radius: 4px;
        transition: all 0.3s ease;

        .el-icon {
          margin-right: 4px;
          font-size: 14px;
        }

        &:hover {
          transform: translateY(-1px);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        }

        &.is-disabled {
          opacity: 0.5;
          cursor: not-allowed;

          &:hover {
            transform: none;
            box-shadow: none;
          }
        }
      }
    }

    .pagination-wrapper {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
}
</style>
